package com.wjd.wshow.service.impl;

import com.wjd.wshow.common.resource.Resource;
import com.wjd.wshow.common.resource.Thumbnailable;
import com.wjd.wshow.common.resource.entity.VideoResource;
import com.wjd.wshow.common.resource.loader.ResourceLoader;
import com.wjd.wshow.common.resource.pojo.ThumbnailResource;
import com.wjd.wshow.service.ThumbnailService;
import com.wjd.wshow.util.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.nio.file.Path;

@Service("ThumbnailService")
public class ThumbnailServiceImpl implements ThumbnailService {

    private static Logger logger = LoggerFactory.getLogger(ThumbnailServiceImpl.class);

    @Override
    public ThumbnailResource createThumbnail(Resource source) {
        if (!(source instanceof Thumbnailable)) {
            return null;
        }
        ThumbnailResource thumbnail = null;
        if (source instanceof VideoResource) {
            thumbnail = createVideoThumbnail((VideoResource) source);
            logger.info("Create video: " + source.getResId() + " thumbnail: " + thumbnail.getPath());
        }
        return thumbnail;
    }

    @Override
    public ThumbnailResource getThumbnail(String id) {
        ThumbnailResource resource = new ThumbnailResource(id);
        return resource;
    }

    @Override
    public void deleteThumbnail(String id) {
        ThumbnailResource resource = new ThumbnailResource(id);
        logger.info("Delete thumbnail: " + id);
        ResourceLoader.getLoader().deleteResource(resource);
    }

    /**
     * 创建视频缩略图
     * @param source 资源
     * @return 缩略图
     */
    private ThumbnailResource createVideoThumbnail(VideoResource source) {
        if (source == null) {
            return null;
        }

        ThumbnailResource thumbnail = getThumbnail(source.getResId());
        try {
            // 删除旧的缩略图已存在
            ResourceLoader.getLoader().deleteResource(thumbnail);
            Path thumbPath = ResourceLoader.getLoader().getAbsPath(thumbnail);
            Path sourcePath = ResourceLoader.getLoader().getAbsPath(source);
            if (sourcePath != null) {
                ResourceUtil.frameThumbnail(sourcePath.toString(), thumbPath.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return thumbnail;
    }

}
